package com.wanghlme.bookstore.controller.client;

import com.wanghlme.bookstore.entity.Userinfo;
import com.wanghlme.bookstore.service.UserinfoService;
import com.wanghlme.bookstore.util.common.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RequestMapping("/client")
@Controller
public class UsersController {

    @Autowired
    private UserinfoService userinfoService;

    @RequestMapping("/signUp")
    @ResponseBody
    public String signUp(@RequestBody Userinfo userinfo) {
        if (userinfo == null) {
            return "failure";
        }
        if (StringUtil.isNullEmptyBlank(userinfo.getUsername())) {
            return "username-null";
        }
        if (StringUtil.isNullEmptyBlank(userinfo.getPassword())) {
            return "password-null";
        }
        log.debug(userinfo.toString());
        Userinfo tmp = userinfoService.signUp(userinfo);
        if (tmp != null) {
            log.debug(tmp.toString());
            return "success";
        } else {
            return "failure";
        }
    }

    @RequestMapping("/signIn")
    @ResponseBody
    public String signIn(HttpServletResponse httpServletResponse
            , HttpServletRequest httpServletRequest
            , @RequestParam("username") String username
            , @RequestParam("password") String password
            , @RequestParam("remember") String remember) {
        if (StringUtil.isNullEmptyBlank(username)) {
            return "username-null";
        }
        if (StringUtil.isNullEmptyBlank(password)) {
            return "password-null";
        }
        Userinfo tmp = userinfoService.signIn(username, password);
        if (tmp == null) {
            return "failure";
        }
        if (StringUtil.isNullEmptyBlank(remember)) {
            Cookie c1 = new Cookie("username", username);
            c1.setMaxAge(60 * 60 * 24 * 30);
            httpServletResponse.addCookie(c1);
            Cookie c2 = new Cookie("password", password);
            c2.setMaxAge(60 * 60 * 24 * 30);
            httpServletResponse.addCookie(c2);
            Cookie c3 = new Cookie("remember", "1");
            c3.setMaxAge(60 * 60 * 24 * 30);
            httpServletResponse.addCookie(c3);
        } else {
            Cookie[] cookies = httpServletRequest.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("username".equals(cookie.getName()) || "password".equals(cookie.getName()) || "remember".equals(cookie.getName())) {
                        cookie.setMaxAge(0);
                        httpServletResponse.addCookie(cookie);
                    }
                }
            }
        }
        return username;
    }

    @RequestMapping("/checkUsername")
    public void checkNameExist(@RequestParam("username") String username, HttpServletResponse response) {
        Integer exist = userinfoService.getUserinfoByAccount(username);
        if (exist > 0) {
            try {
                response.getWriter().write("<font color='red'>此用户名已存在</font>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                response.getWriter().write("<font color='blue'>此用户可用</font>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
/*
    public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UserServlet regist()");

        User user = WebUtils.request2Bean(request, User.class);

        boolean same = checkCode(request);
        if (!same) {
            WebUtils.forword(request, response, "/client/user/regist.jsp", "message", "验证码不正确");
            return;
        }

        boolean success = userService.regist(user);

        if (success) {
            // request.getRequestDispatcher("/client/user/login.html").forward(request,
            // response);
            request.setAttribute("message", "注册成功, 现在可以登陆了!");
            request.getRequestDispatcher("/client/user/login.jsp").forward(request, response);
        } else {
            // response.sendRedirect(request.getContextPath()+"/client/user/regist_error.html");
            request.setAttribute("message", "注册失败, 此用户名已存在!");
            request.getRequestDispatcher("/client/user/regist.jsp").forward(request, response);
        }
    }

    private boolean checkCode(HttpServletRequest request) {
        String code = request.getParameter("code");

        String sessionCode = (String) request.getSession().getAttribute("CODE");

        return code != null && code.equalsIgnoreCase(sessionCode);
    }
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UserServlet login()");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String auto = request.getParameter("auto");

        User user = userService.login(username, password);
        if (user != null) {
            // 将user对象保存到Session中
            WebUtils.login(request, response, user, "me".equals(auto));
            // response.sendRedirect(request.getContextPath()+"/client/user/login_success.html");
            response.sendRedirect(request.getContextPath() + "/client/user/login_success.jsp");
        } else {
            // response.sendRedirect(request.getContextPath()+"/client/user/login_error.html");
            request.setAttribute("message", "用户名或密码错误!");
            request.getRequestDispatcher("/client/user/login.jsp").forward(request, response);
        }
    }
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UserServlet logout()");

        WebUtils.logout(request, response);

        response.sendRedirect(request.getContextPath() + "/client/user/login_success.jsp");
    }
*/
    /* 4. Ajax请求检查用户名是否可用 */

}
